package org.example.lanchain.controller;

import org.example.lanchain.bean.AiAssistant;
import org.example.lanchain.bean.User;
import org.example.lanchain.service.AiAssistantService;
import org.example.lanchain.service.UserService;
import org.example.lanchain.service.AiAssistantStatsService;
import org.example.lanchain.bean.AiAssistantStats;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/assistants")
public class AiAssistantController {

    @Autowired
    private AiAssistantService aiAssistantService;

    @Autowired
    private UserService userService;

    @Autowired
    private AiAssistantStatsService aiAssistantStatsService;

    // 工具方法：从请求中获取当前用户
    private User getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        return userService.getUserByToken(token);
    }

    @PostMapping
    public ResponseEntity<String> createAiAssistant(HttpServletRequest request, @RequestBody AiAssistant aiAssistant) {
        try {
            User user = getCurrentUser(request);
            if (user == null) return new ResponseEntity<>("未登录或token失效", HttpStatus.UNAUTHORIZED);
            aiAssistant.setUserId(user.getId());
            aiAssistantService.createAiAssistant(aiAssistant);
            return new ResponseEntity<>("AI Assistant created successfully!", HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("Failed to create AI Assistant: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<AiAssistant> getAiAssistantById(HttpServletRequest request, @PathVariable Long id) {
        try {
            User user = getCurrentUser(request);
            if (user == null) return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
            AiAssistant aiAssistant = aiAssistantService.getAiAssistantById(id);
            if (aiAssistant != null && aiAssistant.getUserId().equals(user.getId())) {
                return new ResponseEntity<>(aiAssistant, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping
    public ResponseEntity<List<AiAssistant>> getAllAiAssistants(HttpServletRequest request) {
        try {
            User user = getCurrentUser(request);
            if (user == null) return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
            List<AiAssistant> aiAssistants = aiAssistantService.getAllAiAssistants(user.getId());
            return new ResponseEntity<>(aiAssistants, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping
    public ResponseEntity<String> updateAiAssistant(HttpServletRequest request, @RequestBody AiAssistant aiAssistant) {
        try {
            User user = getCurrentUser(request);
            if (user == null) return new ResponseEntity<>("未登录或token失效", HttpStatus.UNAUTHORIZED);
            aiAssistant.setUserId(user.getId());
            aiAssistantService.updateAiAssistant(aiAssistant);
            return new ResponseEntity<>("AI Assistant updated successfully!", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("Failed to update AI Assistant: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteAiAssistant(HttpServletRequest request, @PathVariable Long id) {
        try {
            User user = getCurrentUser(request);
            if (user == null) return new ResponseEntity<>("未登录或token失效", HttpStatus.UNAUTHORIZED);
            AiAssistant aiAssistant = aiAssistantService.getAiAssistantById(id);
            if (aiAssistant == null || !aiAssistant.getUserId().equals(user.getId())) {
                return new ResponseEntity<>("无权限删除", HttpStatus.FORBIDDEN);
            }
            aiAssistantService.deleteAiAssistant(id);
            return new ResponseEntity<>("AI Assistant deleted successfully!", HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("Failed to delete AI Assistant: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 新增：统计数据接口
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getAiAssistantStats(HttpServletRequest request) {
        try {
            User user = getCurrentUser(request);
            if (user == null) return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
            AiAssistantStats stats = aiAssistantStatsService.getStatsByUserId(user.getId());
            Map<String, Object> result = new HashMap<>();
            if (stats != null) {
                result.put("totalUsers", stats.getTotalUsers());
                result.put("totalMessages", stats.getTotalMessages());
                result.put("avgResponseTime", stats.getAvgResponseTime());
                result.put("satisfactionRate", stats.getSatisfactionRate());
                result.put("totalAssistants", stats.getTotalAssistants());
            } else {
                result.put("totalUsers", 0);
                result.put("totalMessages", 0);
                result.put("avgResponseTime", 0);
                result.put("satisfactionRate", 0);
                result.put("totalAssistants", 0);
            }
            return new ResponseEntity<>(result, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
} 